package com.springcloud.minio.feign;

import com.springcloud.commom.api.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class MinioClient implements IMinioClient {

    @Value("${minio.url}")
    private String url;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.backetName}")
    private String backetName;

    @Override
    public R upload(MultipartFile file) {
        try {
            io.minio.MinioClient minioClient = new io.minio.MinioClient(url, accessKey, secretKey);
            InputStream is = file.getInputStream(); //得到文件流
            String fileName = file.getOriginalFilename(); //文件名
            String contentType = file.getContentType();  //类型

            boolean isExist = minioClient.bucketExists(backetName);
            if (!isExist) {
                minioClient.makeBucket(backetName);
            }
            minioClient.putObject(backetName, fileName, is, contentType); //把文件放置Minio桶(文件夹)

            return R.success();
        } catch (Exception e) {
            log.error(e.getMessage());

            return R.fail("上传失败!");
        }
    }

    @Override
    public R getUrl(String fileName) {
        try {
            io.minio.MinioClient minioClient = new io.minio.MinioClient(url, accessKey, secretKey);
            String url = minioClient.presignedGetObject(backetName, fileName);

            Map<String, String> result = new HashMap();
            result.put("url", url);

            return R.data(result);
        } catch (Exception e) {
            return R.fail("获取失败!");
        }
    }
}
